package com.macro.mall.controller;

import cn.hutool.core.util.IdUtil;
import com.macro.mall.common.api.CommonResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author super
 * @title: UploadController
 * @description: TODO
 * @date 2020/8/18 15:01
 */

@Slf4j
@RestController
@Api(tags = "upload", description = "文件上传(upload)")
public class UploadController {


    @Value("${images.path}")
    String path;
    @Value("${images.url}")
    String url;

    public static void main(String[] args) {

    }

    @PostMapping("/upload")
    public CommonResult SingleFileUpLoad(@RequestParam("file") MultipartFile file) {

        //创建输入输出流
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {


            inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            fileName = IdUtil.simpleUUID() + suffixName; // 新文件名
            File targetFile = new File(path + fileName);

            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdir();
            }
            String path = url + fileName;
            if("gif,png,jpg,jpeg".indexOf(suffixName.toLowerCase()) != -1) {
                System.out.println(suffixName);
                Thumbnails.of(targetFile)
                        .scale(0.5f)
                        .outputQuality(0.5f)
                        .toOutputStream(new FileOutputStream(path));
            } else {
                outputStream = new FileOutputStream(targetFile);
                FileCopyUtils.copy(inputStream, outputStream);
            }

            return CommonResult.success(path);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
